package jzqb.dao.impl;

import cnki.tpi.base.DataContext;
import cnki.tpi.base.DataSourceManager;
import cnki.tpi.kbatis.sqlsession.SqlSession;
import cnki.tpi.kbatis.utils.DataSourceUtil;
import haha.life.common.SysTool;
import haha.life.normal.FileUtil;
import haha.life.normal.FileuploadUtils;
import jzqb.bo.AdminQueryBo;
import jzqb.dao.QBZSDao;
import jzqb.po.QBZSPo;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 情报知识数据层实现类
 */
@Repository
public class QBZSDaoImpl implements QBZSDao {

    @Autowired
    private DataSourceManager kbaseDs;

    @Autowired
    private DataContext dataContext;

    @Value("${filePath.fileTemPResource}")
    private String fileTemPResource;

    @Value("${filePath.qbzsFilePath}")
    private String qbzsFilePath;

    @Value("${filePath.qbcgCoverPath}")
    private String qbcgCoverPath;

    @Value("${filePath.qbcgFilePath}")
    private String qbcgFilePath;

    @Value("${filePath.qbzyCoverPath}")
    private String qbzyCoverPath;

    @Value("${filePath.qbzyFilePath}")
    private String qbzyFilePath;

    @Value("${filePath.ztwxFilePath}")
    private String ztwxFilePath;


    @Override
    public Boolean updateQBZS(QBZSPo po) {
        boolean fileRes = true;
        String newDigitFileName = po.getNewDigitFileName();
        String digitFileName = po.getDigitFileName();
        String delete = po.getNeedDelete();
        String dbAbsPath,tempPath,before= "";
        //1. 把新文件从临时目录移动到数据库，并且删除原文件
        if (!"".equals(newDigitFileName) && newDigitFileName != null){
            if (!"".equals(digitFileName) && digitFileName != null){
                String filePath = FileUtil.calculateAbstractPath(digitFileName,qbzsFilePath);
                FileuploadUtils.deleteFileFromDBFile(this.kbaseDs, filePath.substring(0,filePath.lastIndexOf("\\")));
//                FileUtil.deleteFolder(filePath.substring(0,filePath.lastIndexOf("\\")));
            }
            dbAbsPath = FileUtil.calculateAbstractPath(newDigitFileName,qbzsFilePath);
            tempPath = FileUtil.calculateAbstractPath(newDigitFileName,fileTemPResource);
            try {
                FileuploadUtils.moveTempFileToDBFile(this.kbaseDs,tempPath,dbAbsPath);
//                FileuploadUtils.fileMove(tempPath,dbAbsPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
            po.setDigitFileName(newDigitFileName);
        }
        //2. 如果有需要删除的文件则进行删除
        if (!"".equals(delete) && delete != null) {
            before = FileUtil.calculateAbstractPath(delete,qbzsFilePath);
//            FileUtil.deleteFolder(before.substring(0, before.lastIndexOf("\\")));
            FileuploadUtils.deleteFileFromDBFile(this.kbaseDs, before.substring(0, before.lastIndexOf("\\")));
        }
        //3. 更新
        String recStr = FileuploadUtils.generRECfile("fieldsRemap_standard.json","edit", digitFileName,po.getSysID(),po);
        String tableName = SysTool.QBZS_METADATA;
        boolean updateRes = dataContext.updateRecData("SYS_FLD_SYSID", tableName, recStr);
        return updateRes && fileRes;
    }

    @Override
    public Boolean insertQBZS(QBZSPo po) {
        String digitFileName = po.getDigitFileName();
        Integer sysID = po.getSysID();
        //1 写入数据到数据库
        String recStr = FileuploadUtils.generRECfile("fieldsRemap_standard.json","add",digitFileName, sysID,po);
        String tableName = SysTool.QBZS_METADATA;
        boolean insetRes = dataContext.insertRecData(tableName,recStr);
        boolean fileRes = true;
        String dbAbsPath,tempPath = "";
        //2 把文件从 临时目录 移动到 数据库
        if (!"".equals(digitFileName)){
            dbAbsPath = FileUtil.calculateAbstractPath(digitFileName,qbzsFilePath);
            tempPath = FileUtil.calculateAbstractPath(digitFileName,fileTemPResource);
            try {
//                fileRes = FileuploadUtils.fileMove(tempPath,dbAbsPath);
                fileRes = FileuploadUtils.moveTempFileToDBFile(this.kbaseDs,tempPath,dbAbsPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return insetRes && fileRes;
    }

    @Override
    public Boolean deleteQBZS(QBZSPo qbzsPo) {
        //删除文件
        String name = qbzsPo.getDigitFileName();
        Boolean deleteDBFile = true;
        Boolean deleteDB = true;
//        if(!"".equals(name)&& name!= null){
//            String filePath = FileUtil.calculateAbstractPath(name,qbzsFilePath);
//            FileuploadUtils.deleteFileFromDBFile(this.kbaseDs, filePath.substring(0,filePath.lastIndexOf("\\")));
//        }
        //数据库数据删除
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.QBZSDao.deleteQBZS";
        deleteDB = sqlSession.executeDelete(statementId, qbzsPo.getSysID());
        return deleteDB;
    }

    @Override
    public List<QBZSPo> queryQBZS(AdminQueryBo bo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.QBZSDao.queryQBZS";
        return sqlSession.selectList(statementId, bo, false);
    }

    @Override
    public Long count(AdminQueryBo bo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.QBZSDao.count";
        return sqlSession.getCount(statementId, bo);
    }

    @Override
    public boolean batchImport(String tempDir, JSONObject obj, String dbCode) {
        boolean moveRes = false;
        String tableName = dbCode + "_METADATA";
        String fileDir = null;
        String coverDir = null;
        String fileType = null;
        String fileTempPath= null;
        String coverTempPath= null;
        String fileSavePath= null;
        String coverSavePath= null;
        String coverName = "";
        if("JZQBZS".equals(dbCode)){
            fileDir = qbzsFilePath;
        }else if("JZCG".equals(dbCode)){
            fileDir = qbcgFilePath;
            coverDir = qbcgCoverPath;
        }else if("JZZY".equals(dbCode)){
            fileDir = qbzyFilePath;
            coverDir = qbzyCoverPath;
        }else if("YQTZTWX".equals(dbCode)){
            fileDir = ztwxFilePath;
        }
        Object sys_fld_digitfilename = obj.get("SYS_FLD_DIGITFILENAME");
        String digitFileName = "";
        if(sys_fld_digitfilename != null){
            digitFileName = sys_fld_digitfilename.toString();
        }
        if (!"".equals(digitFileName)){
            fileType = digitFileName.substring(digitFileName.lastIndexOf(".") + 1).toUpperCase();
            fileSavePath =digitFileName;
            fileTempPath = tempDir +  "\\" +dbCode +  "\\" +digitFileName;
            obj.put("SYS_FLD_DIGITFILENAME",fileSavePath);
            fileSavePath = FileUtil.calculateAbstractPath(fileSavePath,fileDir);
        }
        //把封面从 临时目录 移动到 数据库
        if(coverDir != null){
            Object cover = obj.get("封面");
            if(!"".equals(cover) && cover!= null){
                coverName = cover.toString();
            }
            if (!"".equals(coverName)){
                digitFileName = coverName;
                coverTempPath = tempDir + "\\" + dbCode + "\\" + coverName;
                coverSavePath = FileUtil.calculateAbstractPath(digitFileName,coverDir);
            }else{
                if (!"".equals(digitFileName) && "PDF".equals(fileType)){
                    coverName = digitFileName.substring(0,digitFileName.lastIndexOf("."))+".png";
                    coverTempPath = tempDir + "\\" + dbCode + "\\" + coverName;
                    coverSavePath = FileUtil.calculateAbstractPath(coverName,coverDir);
                    FileuploadUtils.pdfToPhoto(fileTempPath, coverTempPath);
                    obj.put("封面",coverName);
                }
            }
        }

        //把文件从 临时目录 移动到 数据库
        if (!"".equals(digitFileName)) {
            try {
//                moveRes = FileuploadUtils.moveOneFile(sourcePath,dbAbsPath);
                moveRes = FileuploadUtils.moveTempOneFileToDBFile(this.kbaseDs,fileTempPath,fileSavePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(!"".equals(coverName)) {
            try {
                if(moveRes){
                    moveRes = FileuploadUtils.moveTempOneFileToDBFile(this.kbaseDs,coverTempPath,coverSavePath);
//                        moveRes = FileuploadUtils.fileMove(sourcePath,dbAbsPath);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //3 写入数据到数据库
        String recStr;
        try {
            recStr = FileuploadUtils.generRECfileByJSONObject(obj,dbCode);
        }catch (Exception e){
            return false;
        }
        boolean insetRes = dataContext.insertRecData(tableName,recStr);
        return insetRes && moveRes;

    }

}
